import { constantRoutes } from '@/router'
import Layout from '@/layout/index'
import AuthApi from '@/api/AuthApi'
import defaultSettings from '@/settings'

const { defaultModule } = defaultSettings

// 遍历后台传来的路由字符串，转换为组件对象
function filterAsyncRouters(asyncRouterMap) {
  return asyncRouterMap.filter(route => {
    if (route.component) {
      // Layout组件特殊处理
      if (route.component === 'Layout') {
        route.component = Layout
      } else {
        route.component = loadView(route.component)
      }
    }
    if (route.children != null && route.children && route.children.length) {
      route.children = filterAsyncRouters(route.children)
    } else {
      delete route.children
    }
    return true
  })
}

export const loadView = (view) => { // 路由懒加载
  return (resolve) => require([`@/views/${view}`], resolve)
}

export default {
  namespaced: true,
  state: {
    routes: [],
    addRoutes: [],
    module: defaultModule // 所属模块
  },
  mutations: {
    SET_ROUTES: (state, routes) => {
      state.addRoutes = routes
      state.routes = constantRoutes.concat(routes)
    },
    SET_MODULE: (state, module) => {
      state.module = module
    }
  },
  actions: {
    GenerateRoutes({ commit }) {
      return new Promise(resolve => {
        AuthApi.getRouters().then(response => {
          const accessedRoutes = filterAsyncRouters(response.data)
          accessedRoutes.push({ path: '*', redirect: '/404', hidden: true })
          commit('SET_ROUTES', accessedRoutes)
          resolve(accessedRoutes)
        })
      })
    },
    SetModule({ commit, state }, module) {
      commit('SET_MODULE', module)
    }
  }
}
